var app = getApp();
var ux = require('../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sumff:0,
    selectGood:0,
    yeList:[],
    sumDouble:0,
    products:0,
    coupons:0,
    couponId:null,
    ydi:0,
    pdi:0,
    sum:0,
    remaks: '',
    tongyi: 2,
    dotNull: 1,
    dot: {},
    song: 2,
    orderId: null,
    address: {},
    banrd: {},
    order: {},
    list: [],
    submitUrl:"/api/orders/zhiConfirmOrderFree.do",
    submitPayUrl: "/api/orders/zhiConfirmOrder.do",
    dotUrl: "/api/dot/getLatelyDot.do",
    action: "/api/balance/getOrderInfos.do",
    submit: "{{submit}}"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    this.setData({
      banrdId: wx.getStorageSync("banrdId")
    });
    ux.login(function (protocol) {
      if (protocol.success) {
        wx.setStorageSync("userInfo", protocol.data.userInfo);
        wx.setStorageSync("token", protocol.data.token);
        self.setData({
          userInfo: protocol.data.userInfo
        })
      }
    });
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }
    var params = { orderId: this.data.orderId }
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    ux.request(this.data.action, params, function (protocol) {
      console.log(protocol);
      wx.hideLoading();
      app.globalData.thisBrand = protocol.data.banrd.id;
      console.log("protocol.data.address"+JSON.stringify(protocol.data.address))
      self.setData({
        sum: protocol.data.sumDouble,
        products: protocol.data.products,
        coupons: protocol.data.coupons,
        sumDouble: protocol.data.sumDouble,
        address: protocol.data.address,
        peisong: protocol.data.peisong,
        sumff: ux.acAdd(protocol.data.sumDouble, protocol.data.peisong),
        banrd: protocol.data.banrd,
        order: protocol.data.order,
        list: protocol.data.list,
      })
    }, true);
  },

  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo(dataset.url);
          }
        }
      }, true);
    }
  },

  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  
  gotoSelectAddress: function () {
    wx.navigateTo({
      url: '/pages/member/tab3/adress/adressList',
    })
  },
  songh: function () {
    this.setData({
      sumff: ux.acAdd(this.data.peisong,this.data.sum),
      song: 2
    })
  },
  ziti: function () {
    var self = this;
    if (!this.data.address.id) {
      self.toast("请配置收获地址");
      return false;
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    var params = { banrdId: this.data.banrdId, adressId: this.data.address.id }
    ux.request(this.data.dotUrl, params, function (protocol) {
      console.log(JSON.stringify(protocol.data.dot));
      wx.hideLoading();
      if (protocol.data.type == 1) {
        self.setData({
          dot: protocol.data.dot
        })
        self.setData({
          //sum: ux.acSub(self.data.sum, self.data.peisong),
          song: 1
        })
      } else {
        self.setData({
          song: 2
        })
        self.toast("该品牌当前城市还没有自提网点")
      }
    }, true);

  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  tongyis: function () {
    if (this.data.tongyi == 2) {
      this.setData({
        tongyi: 1
      })
    } else {
      this.setData({
        tongyi: 2
      })
    }
  },
  tijiaos: function (e) {
    let formId = e.detail.formId;
    var self = this;
    if (!this.data.address) {
      this.toast("请填写收货地址");
      return false;
    }
    if (this.data.tongyi == 2) {
      this.toast("请认证阅读支付协议并同意");
      return false;
    }
    if(this.data.song==1){
      if (this.data.sum > 0) {
        //
        this.toPay(formId);
      } else {
        this.toTis(formId);
      }
    }else{
      if (this.data.sumff>0) {
        this.toPay(formId);
      } else {
        this.toTis(formId);
      }
    }
  },
  toPay: function (formId){
    var self=this;
   
    var parmas = { formId: formId, yeIds: JSON.stringify(this.data.yeList),  couponId: Number(this.data.couponId), yemoney:this.data.pdi,ymoney: this.data.ydi,pType: this.data.song, cityId: this.data.address.cityOrigin, remarks: this.data.remaks, xie: 1, adressId: this.data.address.id, orderId: this.data.order.id };
    if (this.data.song == 1) {
      parmas.pfee = 0;
      parmas.dotId = this.data.dot.id;
      parmas.realyMoney = this.data.sum;
    }else{
      parmas.realyMoney = ux.acAdd(this.data.sum,this.data.peisong),
      parmas.pfee = this.data.peisong;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(self.data.submitPayUrl, parmas, function (data) {
      wx.hideLoading();
      if (data.data.type == 1) {
        var order = data.data;
        wx.requestPayment({
          timeStamp: order.timeStamp,
          nonceStr: order.nonceStr,
          package: order.package,
          signType: 'MD5',
          paySign: order.paySign,
          success: function (res) {
            wx.hideLoading();
            self.toast("支付成功");
            wx.redirectTo({
              url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
            })
          },
          fail: function (res) {
            wx.hideLoading();
            wx.showToast({
              title: "支付失败",
              duration: 3000
            })
            wx.redirectTo({
              url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
            })
          }
        })
      } else {
        wx.hideLoading()
        self.toast("支付失败");
        wx.redirectTo({
          url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
        })
      }
    },true)
  },
  toTis: function (formId){
    var self=this;
    var parmas = { formId: formId, yeIds: JSON.stringify(this.data.yeList), couponId: Number(this.data.couponId), yemoney: this.data.pdi, ymoney: this.data.ydi, pfee: this.data.peisong, cityId: this.data.address.cityOrigin, pType: this.data.song, remarks: this.data.remaks, xie: 1, adressId: this.data.address.id, orderId: this.data.order.id };
    if (this.data.song == 1) {
      parmas.dotId = this.data.dot.id;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(self.data.submitUrl, parmas, function (data) {
      wx.hideLoading();
      if (data.data.type == 1) {
        self.toast("提交成功");
        wx.redirectTo({
          url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
        })
      } else {
        self.toast("提交失败")
      }
    })
  },
  remaks: function (e) {
    var value = e.detail.value;
    this.setData({
      remaks: value
    })
  },
  look:function(){
    wx.navigateTo({
      url: '/pages/protocol/explain',
    })
  },
  toProduct:function(){
     wx.navigateTo({
       url: '/pages/member/tab2/products?orderId=' + this.data.orderId + "&yeList=" + JSON.stringify(this.data.yeList),
     })
  },
  toCoupon:function(){
    if(this.data.song==1){
      if (this.data.sum == 0) {
        this.toast("您已选择全部使用余额了不能使用优惠券了");
        return false;
      } 
    }else{
      if (ux.acSub(this.data.sumff, this.data.peisong) == 0) {
        this.toast("您已选择全部使用余额了不能使用优惠券了");
        return false;
      } 
    }
    
    wx.navigateTo({
      url: '/pages/member/tab2/coupons?orderId=' + this.data.orderId +"&couponId="+this.data.couponId,
    })
  },
  gotoDao: function () {
    var item = this.data.dot;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图定位功能将无法使用',
            success: function (res) {
              if (res.cancel) {
                console.info("1授权失败返回数据");

              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      wx.openLocation({
                        latitude: parseFloat(item.latitude),
                        longitude: parseFloat(item.longitude),
                        name: item.coordinateAddress,
                        scale: 28
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.openLocation({
            latitude: parseFloat(item.latitude),
            longitude: parseFloat(item.longitude),
            name: item.coordinateAddress,
            scale: 28
          })
        }
      }
    })
  }
})
